package com.zjgk.hotel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;


import com.zjgk.hotel.dao.mapper.UserMapper;
import com.zjgk.hotel.dao.pojo.User;
import com.zjgk.hotel.service.UserService;
import com.zjgk.hotel.utils.JWTUtils;
import com.zjgk.hotel.vo.Result;
import com.zjgk.hotel.vo.params.WxInfoParams;
import com.zjgk.hotel.vo.params.WxUserLoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.appId}")
    private String appId;

    @Value("${spring.application.name}")
    private String app_name;

    @Autowired
    private UserMapper userMapper;

    public boolean holdNumber(Long userId,String token){
        String account_number = app_name + ".account_number";
        Object old_token = redisTemplate.opsForHash().get(account_number, userId.toString());
        if (old_token != null) {
            redisTemplate.delete(old_token.toString());
        }
        redisTemplate.opsForHash().delete(account_number,userId.toString());
        redisTemplate.opsForHash().put(account_number,userId.toString(),token);
        return true;
    }

    public String checkToken(String token) {
        if (StringUtils.isBlank(token)){
            return  null;
        }

        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null){
            return null;
        }

        String userInfo = redisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(userInfo)){
            return null;
        }
        return userInfo;
    }

    private User userRegister(String phone) {
        User userInfo = new User();
        userInfo.setPhone(phone);
        userInfo.setUsername(phone);
        userInfo.setCreateTime(System.currentTimeMillis());
        userInfo.setLoginDate(System.currentTimeMillis());
        userMapper.insert(userInfo);
        return userMapper.getUserByPhone(phone);
    }


    @Override
    @Transactional
    public Result wxUserLogin(WxUserLoginParams user) {
        try {

            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            String uri = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret="+ secret +"&js_code=" + user.getCode() +"&grant_type=authorization_code";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
            HttpEntity<String> entity = new HttpEntity<String>(headers);
            ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

            WxInfoParams parse = JSONObject.parseObject(response.getBody(), WxInfoParams.class);
            if (parse.getErrcode() != 0){
                return new Result(Result.SERVER_ERROR,"ErrCode :" + parse.getErrcode() +"；"+parse.getErrmsg());
            }

            Long userId = userMapper.getWxCodeById(parse.getOpenid());


            if (userId == null){
                User userInfo = new User();
                userInfo.setPhone(user.getPhone());
                userInfo.setUsername(user.getUsername());
                userInfo.setHeadImg(user.getHeadImg());
                userInfo.setWxCode(parse.getOpenid());
                userInfo.setCreateTime(System.currentTimeMillis());
                userInfo.setLoginDate(System.currentTimeMillis());
                userMapper.insert(userInfo);


                String token = JWTUtils.createToken(userInfo.getId());
                if (holdNumber(userInfo.getId(), token)){
                    User mapperUserInfo = userMapper.getUserInfo(userInfo.getId());
                    redisTemplate.opsForValue().set(token,JSON.toJSONString(mapperUserInfo));
                }

                return new Result(Result.SUCCESS,"成功",token);
            }else{
                String token = JWTUtils.createToken(userId);
                if (holdNumber(userId, token)){
                    User mapperUserInfo = userMapper.getUserInfo(userId);
                    redisTemplate.opsForValue().set(token,JSON.toJSONString(mapperUserInfo));
                }
                return new Result(Result.SUCCESS,"成功",token);
            }
        }catch (Exception e){
            return new Result(Result.SERVER_ERROR,"服务器错误",e.getMessage());
        }

    }

    @Override
    public Result userInfo() {
        return null;
    }
}
